import { defineStore } from 'pinia'
import { AuctionProduct } from '../dto/AuctionProduct.ts';
import { ref } from 'vue'

export const useAuctionStore = defineStore('auction', {
    state: () => {
        return {
            // 选择的竞品信息
            auction_info:<AuctionProduct>{},
            // 竞品开始拍卖标志
            auctionFlag: ref<Boolean>(false),
            // 流拍标志
            notAuctionFlag: ref<Boolean>(false),
            // 拍卖通知
            auctionHandleFlag: ref<boolean>(false),
            // 正在拍卖的标识，用于展示拍卖最新价格
            aucMap: new Map<string, number>(),
            // 竞拍的最新价格，由websocket维护
            newPriceObj:{
                newPrice : 0
            }
        }
    },
    actions: {
        // 修改选择的竞品信息
        updateAuctionInfo(value: AuctionProduct){
            this.auction_info = value;
        },
        // 修改开始拍卖标志
        updateAuctionFlag(newFlag: boolean){
            this.auctionFlag = newFlag;
        },
        // 修改流拍的标志
        updateNotAuctionFlag(flag: boolean){
            this.notAuctionFlag = flag;
        },
        // 修改拍卖通知标识
        upDateauctionHandleFlag(newFlag: boolean){
            this.auctionHandleFlag = newFlag;
        },
        setNewprice(newValue: number | undefined){
            console.log("设置newPrice为:", newValue);
            if(newValue){
                this.newPriceObj.newPrice = newValue
                return true;
            }
        },
        // 设置正在拍卖的Map
        setMyMap(id: string, price: number){
            this.aucMap.set(id, price);
            this.setNewprice(price)
        },
        targgleAuc(){
            for (const key of this.aucMap.keys()) {
                if(this.auction_info.uid == key){
                    const newPrice = this.aucMap.get(key);
                    if (newPrice !== undefined) {
                        this.newPriceObj.newPrice = newPrice;
                        return;
                    }
                }
            }
            this.newPriceObj.newPrice =  0;
        }
    },
    getters:{
        // 计算当前选择的竞品是否处于拍卖，如果处于拍卖则返回最新拍卖价格，否则返回0让其显示底价
        getNewPrice(state): number | undefined{
            // console.log("getters...");
            
            // 遍历map，查看当前选中的id是否在其中
            for (const key in state.aucMap.keys) {
                if(state.auction_info.uid == key){
                    return state.aucMap.get(key)
                }
            }
            return 0;
        }   
    }
})